package org.xtremeobjects.domain.model.ddd;

import java.util.Collection;
import java.util.HashMap;

import org.xtremeobjects.domain.core.di.Injector;
import org.xtremeobjects.domain.model.Clazz;
import org.xtremeobjects.domain.model.ClazzRepository;

public class RepositoryRepository {

	private HashMap<Clazz, Repository> repositories = new HashMap<Clazz, Repository>();
	
	public Collection<Repository> allInstances() {
		return repositories.values();
	}
	
	public Repository findOrCreateByClazz( Clazz clazz ) {
		Repository rep = repositories.get(clazz);
		if(rep!=null) {
			return rep;
		} 
		return RepositoryFactory.CreateForClazz(clazz);
	}
	
	public Repository findOrCreateByClass( Class<?> cl ) {
		return findOrCreateByClazz( toClazz(cl) );
	}

	private Clazz toClazz(Class<?> cl) {
		return getClazzRepository().findOrCreateByClass(cl);
	}

	private ClazzRepository getClazzRepository() {
		return Injector.getInstance(ClazzRepository.class);
	}
	
}
